﻿using Abp.Domain.Repositories;
using SportsPlatform.Base;
using SportsPlatform.Dto.SportBusiness.AchievementPunishmentInfo;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Query.SportBusiness.AchievementPunishmentInfo;
using SportsPlatform.SportBusiness.ISportBusiness;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.Consts;
using SportsPlatform.Jwt;
using Abp.Application.Services;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;
using SportsPlatform.SqlExecuter;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 成绩惩罚记录接口实现
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class AchievementPunishmentInfoService : SportsPlatformAppServiceBase, IAchievementPunishmentInfoService
    {
        //成绩过点记录信息
        private readonly IRepository<AchievementPunishmentInfo, Guid> _achievementPunishmentInfoRepository;

        private readonly IRepository<UserInfo, Guid> _userinfoRepository;

        private readonly IRepository<CompetitionAchievementInfo, Guid> _comachiRepository;

        private readonly IRepository<Employee, Guid> _employeeRepository;

        private readonly IRepository<CompeteTeam, Guid> _comteamRepository;

        private readonly ISqlExecuterRepository _sqlExecuterRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        public AchievementPunishmentInfoService(IRepository<AchievementPunishmentInfo, Guid> achievementPunishmentInfoRepository,
            IRepository<CompetitionAchievementInfo, Guid> comachiRepository, IRepository<Employee, Guid> employeeRepository,
            IRepository<CompeteTeam, Guid> comteamRepository,
            ISqlExecuterRepository sqlExecuterRepository,
            IRepository<UserInfo, Guid> userinfoRepository, IHttpContextAccessor context) : base(context)
        {
            _achievementPunishmentInfoRepository = achievementPunishmentInfoRepository;
            _userinfoRepository = userinfoRepository;
            _comachiRepository = comachiRepository;
            _comteamRepository = comteamRepository;
            _employeeRepository = employeeRepository;
            _sqlExecuterRepository = sqlExecuterRepository;
        }

        /// <summary>
        /// 新增成绩惩罚信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddAchievementPunishmentInfo(AddAchievementPunishmentInfoQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                AchievementPunishmentInfo achievementPunishmentInfo = ObjectMapper.Map<AchievementPunishmentInfo>(query);
                achievementPunishmentInfo.CreateTime = DateTime.Now;
                achievementPunishmentInfo.CreateUserId = token.Id;
                achievementPunishmentInfo.PenaltyTime = DateTime.Now;
                achievementPunishmentInfo.PenaltyStatus = true;
                await _achievementPunishmentInfoRepository.InsertAsync(achievementPunishmentInfo);
                baseResultDto.IsSuccess = true;
                baseResultDto.Code = HttpResultCode.Success;
                baseResultDto.Message = "添加成功";
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 成绩惩罚信息同步
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> PunishmentInfoSynchronization(List<PunishmentInfoSynchronizationQuery> query)
        {
            BaseResultDto resultDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                //同步之前删除之前项目Id的分组
                var querypunilist = query
                    .GroupBy(group => new { group.CompetitionAchievementId })
                    .Select(group => group.FirstOrDefault())
                    .ToList();
                querypunilist.ForEach(item =>
                {
                    var sql = "UPDATE T_B_AchievementPunishmentInfo SET IsDeleted=1,DeleteTime='" + DateTime.Now + "',DeleteUserId='" + token.Id + "' where CompetitionAchievementId='" + item.CompetitionAchievementId + "'";
                    _sqlExecuterRepository.Execute(sql, null);
                });
                var userlist = await _userinfoRepository.GetAllListAsync();
                var emplist = await _employeeRepository.GetAllListAsync();
                var comteamlist = await _comteamRepository.GetAllListAsync();
                var achilist = await _comachiRepository.GetAllListAsync();
                var punilist = await _achievementPunishmentInfoRepository.GetAllListAsync();
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Fail;
                foreach (var item in query)
                {
                    #region 验证数据

                    if (achilist.FirstOrDefault(info => info.Id == item.CompetitionAchievementId) == null)
                    {
                        resultDto.Message += $"赛事成绩Id:{item.CompetitionAchievementId}不存在;";
                        continue;
                    }
                    if (emplist.FirstOrDefault(info => info.Id == item.EmployeeId) == null && comteamlist.FirstOrDefault(info => info.Id == item.EmployeeId) == null)
                    {
                        resultDto.Message += $"{item.EmployeeId}不存在参赛用户并不存在参赛团队";
                        continue;
                    }
                    if (item.CreateUserId != null && userlist.FirstOrDefault(info => info.Id == item.CreateUserId) == null)
                    {
                        resultDto.Message += $"创建用户Id:{item.CreateUserId}不存在;";
                        continue;
                    }
                    #endregion

                    //如果id不存在就新建,否则就更新
                    var info = item.Id == null ? null : punilist.FirstOrDefault(info => info.Id == item.Id);
                    if (info == null)
                    {
                        var pointinfo = ObjectMapper.Map<AchievementPunishmentInfo>(item);
                        pointinfo.Id = item.Id ?? Guid.NewGuid();
                        if (item.CreateTime == null)
                        {
                            pointinfo.CreateTime = DateTime.Now;
                        }
                        if (item.CreateUserId == null)
                        {
                            pointinfo.CreateUserId = token.Id;
                        }
                        await _achievementPunishmentInfoRepository.InsertAsync(pointinfo);
                    }
                    else
                    {
                        info.CompetitionAchievementId = item.CompetitionAchievementId;
                        info.EmployeeId = item.EmployeeId;
                        info.CompeteName = item.CompeteName;
                        info.PenaltyEvent = item.PenaltyEvent;
                        info.PenaltyReason = item.PenaltyReason;
                        info.PenaltyTime = item.PenaltyTime;
                        info.PenaltyStatus = item.PenaltyStatus;
                        info.RevokeTime = item.RevokeTime ?? null;
                        info.CreateTime = item.CreateTime ?? DateTime.Now;
                        info.CreateUserId = item.CreateUserId ?? token.CreateUserId;
                        info.IsDeleted = item.IsDeleted ?? false;
                        info.UpdateTime = null;
                        info.UpdateUserId = null;
                        info.DeleteTime = null;
                        info.DeleteUserId = null;
                        await _achievementPunishmentInfoRepository.UpdateAsync(info);
                    }
                    resultDto.IsSuccess = true;
                    resultDto.Code = HttpResultCode.Success;
                }
                resultDto.Message = string.IsNullOrEmpty(resultDto.Message) ? "操作成功！" : resultDto.Message;
            }
            catch (Exception e) { }
            return resultDto;
        }
        /// <summary>
        /// 分页获取赛事成绩惩罚记录信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<AchievementPunishmentInfoDto>> GetAchievementPunishmentInfo(GetAchievementPunishmentInfoPageQuery query)
        {
            PagePagingDto<AchievementPunishmentInfoDto> pagePagingDto = new();
            try
            {

                if (query.CompetitionAchievementId == Guid.Empty)
                {
                    pagePagingDto.IsSuccess = false;
                    pagePagingDto.Code = HttpResultCode.Fail;
                    pagePagingDto.Message = "Id不能为空！";
                    return pagePagingDto;
                }
                var achievementPunishmentInfoList = await _achievementPunishmentInfoRepository.GetAllListAsync(info => info.CompetitionAchievementId == query.CompetitionAchievementId && info.IsDeleted == false);
                var achievementPunishmentInfoPage = achievementPunishmentInfoList.OrderByDescending(info => info.CreateTime)
                     .Skip((query.PageIndex - 1) * query.PageSize)
                     .Take(query.PageSize)
                     .ToList();
                if (achievementPunishmentInfoPage != null && achievementPunishmentInfoPage.Count > 0)
                {
                    pagePagingDto.IsSuccess = true;
                    pagePagingDto.Code = HttpResultCode.Success;
                    pagePagingDto.TotalCount = achievementPunishmentInfoList.Count;
                    pagePagingDto.TotalPage = achievementPunishmentInfoList.Count % query.PageSize == 0 ? achievementPunishmentInfoList.Count / query.PageSize : achievementPunishmentInfoList.Count / query.PageSize + 1;
                    var dtos = ObjectMapper.Map<List<AchievementPunishmentInfoDto>>(achievementPunishmentInfoPage);
                    var userlist = await _userinfoRepository.GetAllListAsync();
                    try
                    {
                        dtos.ForEach(item => { item.OperatorUser = (item.UpdateUserId == null || item.UpdateUserId == Guid.Empty) ? userlist.FirstOrDefault(info => info.Id == item.CreateUserId).UserName : userlist.FirstOrDefault(info => info.Id == item.UpdateUserId).UserName; });
                    }
                    catch { }
                    pagePagingDto.Data = dtos;

                    pagePagingDto.Message = "查询成功";
                }
                else
                {
                    pagePagingDto.IsSuccess = false;
                    pagePagingDto.Code = HttpResultCode.SqlError;
                    pagePagingDto.Message = "未查询到数据！";
                    return pagePagingDto;
                }
            }
            catch (Exception e)
            {
                pagePagingDto.IsSuccess = false;
                pagePagingDto.Code = HttpResultCode.Error;
                pagePagingDto.Message = e.Message.ToString();
            }
            return pagePagingDto;
        }

        /// <summary>
        /// 更新成绩惩罚信息是否撤销
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateAchievementPunishmentInfoRevoke(UpdateAchievementPunishmentInfoRevokeQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                AchievementPunishmentInfo achievementPunishmentInfo = await _achievementPunishmentInfoRepository.FirstOrDefaultAsync(info => info.Id == query.Id);
                if (achievementPunishmentInfo != null)
                {
                    achievementPunishmentInfo.PenaltyStatus = query.PenaltyStatus;
                    achievementPunishmentInfo.RevokeTime = DateTime.Now;
                    achievementPunishmentInfo.UpdateTime = DateTime.Now;
                    achievementPunishmentInfo.UpdateUserId = token.Id;
                    await _achievementPunishmentInfoRepository.UpdateAsync(achievementPunishmentInfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "更新成功";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.SqlError;
                    baseResultDto.Message = "未查询到Id信息！" + query.Id.ToString();
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }
    }
}
